<template>
	<view class="pl-3-1 text-hide" :data-comp-type="compType" :data-select-type="selectType">
		<view class="flex flex-row py-3-1" :class="{ 'items-center': isAlignCenter }">
			<!------------------------------------------label start------------------------------------------>
			<view
				class="row-center"
				v-if="title"
				:class="[titleWidth ? 'mr-1' : 'mr-3-1', isAlignCenter ? '' : 'items-start']"
				:style="titleWidth ? { width: titleWidth + 'px' } : {}"
			>
				<text class="text-m" :class="[isError ? 'color-error' : 'color-main']">
					<slot name="labelTextSuffix" />{{ title }}
				</text>
				<text class="text-l color-error ml-1" v-if="required">*</text>
			</view>
			<!------------------------------------------label end------------------------------------------>
			<!------------------------------------------content start------------------------------------------>
			<view v-if="compType === 'numberSelect'" class="flex-1" />
			<view v-else class="flex-1" @click="handleContent">
				<DetailTextarea
					v-if="compType === 'textarea'"
					:placeholder="placeholder"
					:maxlength="maxlength || 100"
					:extraStyle="'min-height:160rpx;padding-top:4rpx;'"
					v-model="innerValue"
				></DetailTextarea>
				<DatetimePicker
					v-else-if="compType === 'selectTime'"
					v-model="innerValue"
					:start="+new Date()"
					:hideSecond="true"
				>
					<view>
						<text v-if="innerValue" class="text-m color-main">{{ innerValue }}</text>
						<text v-else class="color-disable text-m">{{ placeholder }}</text>
					</view>
				</DatetimePicker>
				<picker v-else-if="compType === 'select' && selectType === 'area'" mode="region" :value="innerValue" @change="regionChange">
					<text
						class="text-m"
						:class="[innerSelectText ? 'color-main' : 'color-disable']"
					>
						{{ innerSelectText || placeholder }}
					</text>
				</picker>
				<text v-else-if="compType === 'imageSelect'" class="text-m color-secondary">
					{{ placeholder }}
				</text>
				<text
					v-else-if="compType === 'select'"
					class="text-m"
					:class="[innerSelectText ? 'color-main' : 'color-disable']"
				>
					{{ innerSelectText || placeholder }}
				</text>
				<input
					v-else
					class="text-m"
					type="text"
					:placeholder="placeholder"
					:placeholder-style="'color: ' + SlStyle.disableColor"
					:maxlength="maxlength || -1"
					v-model="innerValue"
				/>
			</view>
			<template v-if="compType === 'numberSelect'">
				<view
					class="px-3-1"
					hover-class="opacity-60"
					hover-stay-time="50"
					hover-start-time="0"
					@click="handleNumberValue(-1)"
				>
					<text class="iconfont icon-jianshao" :class="[innerValue <= min ? 'color-disable' : 'color-active']"></text>
				</view>
				<view class="text-center" style="width: 42rpx">
					<text class="text-l color-main text-m">{{ innerValue }}</text>
				</view>
				<view
					class="px-3-1"
					hover-class="opacity-60"
					hover-stay-time="50"
					hover-start-time="0"
					@click="handleNumberValue(1)"
				>
					<text
						class="iconfont icon-tianjia"
						:class="[innerValue >= maxlength ? 'color-disable' : 'color-active']"
					></text>
				</view>
			</template>
			<!------------------------------------------content end------------------------------------------>
			<!------------------------------------------suffix start------------------------------------------>
			<view
				v-if="selectIcon"
				@click.stop="handleIcon"
				class="px-2-2 relative ml-2-2"
				hover-class="opacity-60"
				hover-stay-time="50"
				hover-start-time="0"
			>
				<view class="absolute left-0 bg-primary-op20 top-0" style="width: 1px; height: 48rpx" />
				<Icon :name="selectIcon" extraClass="color-main" />
			</view>
			<view v-else-if="compType === 'selectTime' || compType === 'select'" class="px-3-1">
				<text class="iconfont icon-you text-l color-secondary"></text>
			</view>
			<view v-else-if="compType !== 'numberSelect'" :style="{ width: '32rpx' }" />
			<!------------------------------------------suffix end------------------------------------------>
		</view>
		<MediaListUpload
			v-if="compType === 'imageSelect'"
			:num="maxlength || 6"
			ref="imgListRef"
			:upload-immediate="true"
			@change="imgListChange"
			@upload="$emit('upload', $event)"
		/>
		<view class="h-min bg-primary-op20" v-if="border" />
		<!-- popup modal start -->
		<!-- <TreePicker
			v-if="selectType === 'area'"
			ref="regionPicker"
			:show-root="false"
			title="选择所在地区"
			pinyin-sort
			:fieldNames="{ key: 'id', title: 'name' }"
			:getData="getRegionData"
			@visible-change="$emit('popupVisibleChange', $event)"
			@pick="handleRegionPick"
		/> -->
	</view>
</template>

<script setup>
import SlStyle from '../../../style/style.js';
import { ref, watch, computed, onBeforeUnmount, inject, onMounted, nextTick } from 'vue';
import DetailTextarea from '../detail-textarea/detail-textarea.vue';
import Icon from '../../business/icon/icon.vue';
import { verifyByToast } from '../../../utils/verify.js';
import { isNullOrUndefOrEmpty } from '../../../utils/common.js';
// import TestRegionData from './test-region-data.js';
import TreePicker from '../tree-picker/tree-picker.vue';
import MediaListUpload from '../media-list-upload/media-list-upload.vue';
import DatetimePicker from '../../lib/datetime-picker/datetime-picker.vue';
// import { getDistrictByPid } from '@/base/api/common.js';

const props = defineProps({
	//组件类型 panel inputOrSelect textInput numberSelect imageSelect selectTime eqGroup textarea select
	compType: String,
	//选择类型 customer address device scan area
	selectType: String,
	title: String,
	required: Boolean,
	requiredMessage: String,
	placeholder: String,
	maxlength: Number,
	value: [String, Number, Object, Array],
	min: {
		type: Number,
		default: 1,
	},
	pattern: String,
	patternMessage: String,
	/**/
	titleWidth: Number,
	border: Boolean,
	selectText: String,
	relateField: Array,
	uuid: String,
});
const emits = defineEmits([
	'update:value',
	'update:selectText',
	'touchSelIcon',
	'popupVisibleChange',
	'numberChange',
	'upload',
	'select',
]);
function emitSelect(e) {
	emits('select', {
		compType: props.compType,
		selectType: props.selectType,
		e,
	});
}

const imgListRef = ref();
const useFormItem = inject('useFormItem', null);
const selectTypeSetting = {
	customer: {
		selectIcon: 't-icon-kehu',
	},
	scan: {
		selectIcon: 't-icon-saoma',
	},
	device: {
		selectIcon: 't-icon-device-active',
	},
	address: {
		selectIcon: 'icon-dingwei',
	},
};
const selectIcon = computed(() => {
	const target = selectTypeSetting[props.selectType];
	return target ? target.selectIcon : null;
});

const isError = ref(false);
const isAlignCenter = computed(() => {
	return props.compType !== 'textarea' && props.compType !== 'imageSelect';
});

const innerValue = ref('');
const innerSelectText = ref('');
let triggerPropsValue = true;
watch(innerValue, (v) => {
	triggerPropsValue = false;
	emits('update:value', v);
	isError.value = false;
	nextTick(() => {
		triggerPropsValue = true;
	});
});
watch(
	() => props.value,
	(v) => {
		if (!triggerPropsValue) return;
		innerValue.value = v;
		if (props.selectType === 'area') {
			innerSelectText.value = v.join("");
		} else if (props.compType === 'imageSelect') {
			if (imgListRef.value) {
				imgListRef.value.setImgData(v);
			}
		}
	},
	{
		immediate: true,
	}
);
if (props.compType === 'numberSelect') {
	innerValue.value = props.min;
}
watch(innerSelectText, (v) => {
	emits('update:selectText', v);
});
watch(
	() => props.selectText,
	(v) => {
		innerSelectText.value = v;
	}
);

function handleIcon() {
	emits('touchSelIcon');
	if (props.selectType === 'address') {
		uni.showLoading({
			title: '加载中',
			mask: true,
		});
		uni.getSetting({
			success(res) {
				if (!res.authSetting['scope.userLocation']) {
					uni.authorize({
						scope: 'scope.userLocation',
						success() {
							chooseLocation();
						},
						fail(e) {
							console.log('======>authorize fail', e);
						},
					});
				} else {
					chooseLocation();
				}
			},
			complete() {
				uni.hideLoading();
			},
			fail(e) {
				console.log('======>getSetting fail', e);
			},
		});
	} else if (props.selectType === 'scan') {
		uni.scanCode({
			success: (res) => {
				// console.log('条码类型：' + res.scanType);
				// console.log('条码内容：' + res.result);
				innerValue.value = res.result;
			},
		});
	} else if (props.selectType === 'device') {
		uni.navigateTo({
			url: '/pages/select-device/select-device',
			success(e) {
				e.eventChannel.emit('data', {
					handleDevice(data) {
						// console.log("==============>select-device",data);
						innerValue.value = data.productSerialNumber;
						if (props.relateField && useFormItem) {
							useFormItem.setValueByRelateField(data, props.relateField, props.uuid);
						}
					},
				});
			},
		});
	} else if (props.selectType === 'customer') {
		uni.navigateTo({
			url: '/pages/select-customer/select-customer',
			success(e) {
				e.eventChannel.emit('data', {
					handleSelect(data) {
						data = { ...data };
						innerValue.value = data.terminalUsername;
						if (props.relateField && useFormItem) {
							useFormItem.setValueByRelateField(data, props.relateField);
						}
					},
				});
			},
		});
	}
}
/**
 * numberSelect
 */
function handleNumberValue(step) {
	let newValue = innerValue.value + step;
	const max = props.maxlength || 20;
	if (newValue < props.min) {
		newValue = props.min;
	} else if (newValue > max) {
		newValue = max;
	}
	if (innerValue.value !== newValue) {
		innerValue.value = newValue;
		emits('numberChange', {
			step,
		});
	}
}

/**
 * address and region
 */
function chooseLocation() {
	uni.chooseLocation({
		success(e) {
			// console.log("=====>chooseLocation",e);
			//{address: "广东省佛山市顺德区兴隆十路8号", latitude: 22.980202, name: "广东申菱环境系统股份有限公司", errMsg: "chooseLocation:ok", longitude: 113.21539}
			// innerSelectText.value = e.address;
			innerValue.value = e.address;
			emitSelect(e);
		},
		fail(e) {
			console.log("========>chooseLocation fail", e);
		}
	});
}
// const regionData = ref(TestRegionData);
function handleContent() {
	if (props.selectType === 'area') {
	}
}
function regionChange(e){
	//{detail: {value: ["北京市", "北京市", "东城区"],code: ["110000", "110100", "110101"]}}
	innerValue.value = e.detail.value;
	innerSelectText.value = e.detail.value.join("");
}
/**
 * imgSelect
 */
function imgListChange(imgList) {
	innerValue.value = imgList.map((el) => el.src);
}
onMounted(() => {
	if (imgListRef.value) {
		imgListRef.value.setImgData(innerValue.value);
	}
});
/**
 * expose
 */
function getRequiredMessage() {
	if (props.requiredMessage) return props.requiredMessage;
	let prefix = '请输入';
	if (props.compType === 'inputOrSelect') {
		prefix = '请输入或选择';
	} else if (['imageSelect', 'selectTime', 'select'].includes(props.compType)) {
		prefix = '请选择';
	}
	return prefix + props.title;
}
const exposeObj = {
	verify() {
		if (imgListRef.value) {
			const re = imgListRef.value.isSelect();
			isError.value = !re;
			return re;
		} else {
			// console.log(props.title, innerValue.value);
			const re = verifyByToast(innerValue.value, {
				pattern: props.pattern,
				patternMes: props.patternMessage,
				required: props.required,
				requiredMes: getRequiredMessage(),
			});
			isError.value = !re;
			return re;
		}
	},
	async excute() {
		// if (imgListRef.value) {
		// 	const uploadUrls = await imgListRef.value.upload1by1();
		// 	innerValue.value = uploadUrls;
		// }
	},
};
defineExpose(exposeObj);

let exposeObjKey = null;
onMounted(() => {
	if (useFormItem) {
		exposeObjKey = useFormItem.setExpose(exposeObj);
	}
});
onBeforeUnmount(() => {
	if (useFormItem && exposeObjKey) {
		useFormItem.removeExpose(exposeObjKey);
	}
});
</script>

<style></style>
